package com.cloud.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

/**
 * 1Cloud1
 * @author Administrator
 * @since 2016-1-16
 * @version 1.0 
 */
@SuppressWarnings("rawtypes")
public class JsonUtil {
	
	/**
	 * 解析JSON为Map对象
	 * @param json
	 * @return
	 */
	public static Map<String, String> getMapFromJson(String json) {
		Map<String, String> paramMap = new HashMap<String, String>();
		try {
			JSONObject obj = new JSONObject(json).getJSONObject("template");
			JsonParser jsonParser = new JsonParser();
			Iterator it = obj.keys();
			while (it.hasNext()) {
				String key = (String) it.next();
				String value = obj.getString(key);
				if("templetid".equals(key)){
					paramMap.put("templetid", value);
					continue;
				}
				JsonElement jElement = jsonParser.parse(value);
				if(jElement.isJsonObject()){
					JSONObject jsonobject = obj.getJSONObject(key);
					String order = jsonobject.getString("order");
					String type = jsonobject.getString("type");
					String data = jsonobject.getString("data");
					JsonElement _jElement = jsonParser.parse(data);
					if(_jElement.isJsonObject()){
						JSONObject datajson = jsonobject.getJSONObject("data");
						if("redio".equalsIgnoreCase(type)){
							paramMap.put("columnredio_".concat(order), datajson.getString("columnredio"));
						}
						if("check".equalsIgnoreCase(type)){
							String params = jsonobject.getString("param");
							for(int index = 1; index <= params.split(",").length; index++){
								paramMap.put("columncheck_".concat(order).concat("_").concat(String.valueOf(index)), datajson.getString("columncheck".concat(String.valueOf(index))));
							}
							paramMap.put("remarks_".concat(order), datajson.getString("remarks"));
						}
					}
					if(_jElement.isJsonArray()){
						JSONArray dataarray = jsonobject.getJSONArray("data");
						if("select".equalsIgnoreCase(type)){
							StringBuffer buffer = new StringBuffer();
							for (int i = 0; i < dataarray.length(); i++) {
								JSONObject _json = dataarray.getJSONObject(i);
								buffer.append(_json.getString("key")).append("--").append(_json.getString("value")).append(",");
							}
							paramMap.put("columnselect_".concat(order), buffer.toString());
						}
						if("keyvalue".equalsIgnoreCase(type)){
							StringBuffer buffer = new StringBuffer();
							for (int i = 0; i < dataarray.length(); i++) {
								JSONObject _json = dataarray.getJSONObject(i);
								StringBuffer _buffer = new StringBuffer();
								for(int index = 1; index <= jsonobject.getString("param").split(",").length; index++){
									_buffer.append("--").append(_json.getString("key".concat(String.valueOf(index))));
								}
								if(_buffer.toString().length() == 0)
									continue;
								buffer.append(_buffer.toString()).append(",");
							}
							paramMap.put("columnkeyvalue_".concat(order), buffer.toString());
						}
						if("text".equalsIgnoreCase(type)){
							paramMap.put("columntext_".concat(order), data.replaceAll("\"", "").replaceAll("\\[", "").replaceAll("\\]", ""));
						}
					}
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return paramMap;
	}

	public static void main1(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
		Map<String, Object> root = new HashMap<String, Object>();
		Map<String, Object> rootMap = new HashMap<String, Object>();
		rootMap.put("templetName", "tmp_syc");
		rootMap.put("currDate", "2016-01-06");

		Map<String, String> nodeMap1 = new HashMap<String, String>();
		nodeMap1.put("day", "1");
		nodeMap1.put("night", "1");
		nodeMap1.put("abnormal", "无");
		rootMap.put("fyqk", nodeMap1);

		List<Map<String, String>> nodeList1 = new ArrayList<Map<String, String>>();
		Map<String, String> _nodeListMap1 = new HashMap<String, String>();
		_nodeListMap1.put("type", "类型1");
		_nodeListMap1.put("number", "100");
		nodeList1.add(_nodeListMap1);
		Map<String, String> _nodeListMap2 = new HashMap<String, String>();
		_nodeListMap2.put("type", "类型2");
		_nodeListMap2.put("number", "200");
		nodeList1.add(_nodeListMap2);
		Map<String, String> _nodeListMap3 = new HashMap<String, String>();
		_nodeListMap3.put("type", "类型3");
		_nodeListMap3.put("number", "300");
		nodeList1.add(_nodeListMap3);
		rootMap.put("xtqk", nodeList1);

		List<Map<String, String>> nodeList2 = new ArrayList<Map<String, String>>();
		Map<String, String> _nodeList2Map1 = new HashMap<String, String>();
		_nodeList2Map1.put("type", "运动1");
		_nodeList2Map1.put("number", "70000");
		nodeList2.add(_nodeList2Map1);
		Map<String, String> _nodeList2Map2 = new HashMap<String, String>();
		_nodeList2Map2.put("type", "运动2");
		_nodeList2Map2.put("number", "80000");
		nodeList2.add(_nodeList2Map2);
		rootMap.put("ydqk", nodeList2);

		Map<String, String> nodeMap2 = new HashMap<String, String>();
		nodeMap2.put("remarks", "无其他");
		rootMap.put("qtyyqk", nodeMap2);
		root.put("template", rootMap);
		System.out.println(root);
		
		ObjectMapper mapper = new ObjectMapper();
		String result = mapper.writeValueAsString(root);
		System.out.println(result);
		Map<String, Object> _root = parseJsonStr(result);
		System.out.println("==========================================");
		System.out.println(_root);
	}

	private static Map<String, Object> parseJsonStr(String str) {
		Map<String, Object> root = new HashMap<String, Object>();
		Map<String, Object> rootMap = new HashMap<String, Object>();
		try {
			JSONObject obj = new JSONObject(str).getJSONObject("template");
			JsonParser jsonParser = new JsonParser();
			Iterator it = obj.keys();
			while (it.hasNext()) {
				String key = (String) it.next();
				String value = obj.getString(key);
				System.out.println(key + "=" + value);
				if("currDate".equals(key) || "templetName".equals(key)){
					rootMap.put(key, value);
					continue;
				}
				JsonElement jElement = jsonParser.parse(value);
				if(jElement.isJsonArray()){
					rootMap.put(key, parseJsonList(obj, key));
				}
				if(jElement.isJsonObject()){
					rootMap.put(key, parseJsonMap(obj, key));
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		root.put("template", rootMap);
		return root;
	}
	
	private static List<Map<String, String>> parseJsonList(JSONObject obj, String key){
		List<Map<String, String>> nodeList = new ArrayList<Map<String, String>>();
		JSONArray array;
		try {
			array = obj.getJSONArray(key);
			for (int i = 0; i < array.length(); i++) {
				JSONObject jsonobject = array.getJSONObject(i);
				Map<String, String> _map = new HashMap<String, String>();
				Iterator it = jsonobject.keys();
				while (it.hasNext()) {
					String _key = (String) it.next();
					String _value = jsonobject.getString(_key);
					_map.put(_key, _value);
				}
				nodeList.add(_map);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return nodeList;
	}
	
	private static Map<String, String> parseJsonMap(JSONObject obj, String key){
		Map<String, String> nodeMap = new HashMap<String, String>();
		try {
			JSONObject jsonobject = obj.getJSONObject(key);
			Iterator it = jsonobject.keys();
			while (it.hasNext()) {
				String _key = (String) it.next();
				String _value = jsonobject.getString(_key);
				nodeMap.put(_key, _value);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return nodeMap;
	}
}
